package com.stooscloud.base.xmlsax;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.*;
import java.util.*;

/**
 * 基于dom4j的工具包
 */
public class DOMUtils {
    /**
     * 通过文件的路径获取xml的document对象
     *
     * @param path  文件的路径
     * @return      返回文档对象
     */
    public static Document getXMLByFilePath(String path) {
        if (null == path) {
            return null;
        }
        Document document = null;
        try {
            SAXReader reader = new SAXReader();
            document = reader.read(new File(path));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return document;
    }

    /**
     * 通过xml字符获取document文档
     * @param xmlstr    要序列化的xml字符
     * @return          返回文档对象
     * @throws DocumentException
     */
    public static Document getXMLByString(String xmlstr) throws DocumentException {
        if(xmlstr==""||xmlstr==null){
            return null;
        }
        Document document = DocumentHelper.parseText(xmlstr);
        return document;
    }

    /**
     * 获取某个元素的所有的子节点
     * @param node  制定节点
     * @return      返回所有的子节点
     */
    public static List<Element> getChildElements(Element node) {
        if (null == node) {
            return null;
        }
        @SuppressWarnings("unchecked")
        List<Element> lists = node.elements();
        return lists;
    }

    /**
     * 获取指定节点的子节点
     * @param node          父节点
     * @param childnode     指定名称的子节点
     * @return              返回指定的子节点
     */
    public static Element getChildElement(Element node,String childnode){
        if(null==node||null == childnode||"".equals(childnode)){
            return null;
        }
        return node.element(childnode);
    }

    /**
     * 获取所有的属性值
     * @param node
     * @param arg
     * @return
     */
    public static Map<String, String> getAttributes(Element node, String...arg){
        if(node==null||arg.length==0){
            return null;
        }
        Map<String, String> attrMap = new HashMap<String,String>();
        for(String attr:arg){
            String attrValue = node.attributeValue(attr);
            attrMap.put(attr, attrValue);
        }
        return attrMap;
    }

    /**
     * 获取element的单个属性
     * @param node      需要获取属性的节点对象
     * @param attr      需要获取的属性值
     * @return          返回属性的值
     */
    public static String getAttribute(Element node,String attr){
        if(null == node||attr==null||"".equals(attr)){
            return "";
        }
        return node.attributeValue(attr);
    }

    /**
     * 添加孩子节点元素
     *
     * @param parent
     *            父节点
     * @param childName
     *            孩子节点名称
     * @param childValue
     *            孩子节点值
     * @return 新增节点
     */
    public static Element addChild(Element parent, String childName, String childValue) {
        Element child = parent.addElement(childName);// 添加节点元素
        child.setText(childValue == null ? "" : childValue); // 为元素设值
        return child;
    }

    /**
     * DOM4j的Document对象转为XML报文串
     *
     * @param document
     * @param charset
     * @return 经过解析后的xml字符串
     */
    public static String documentToString(Document document, String charset) {
        StringWriter stringWriter = new StringWriter();
        OutputFormat format = OutputFormat.createPrettyPrint();// 获得格式化输出流
        format.setEncoding(charset);// 设置字符集,默认为UTF-8
        XMLWriter xmlWriter = new XMLWriter(stringWriter, format);// 写文件流
        try {
            xmlWriter.write(document);
            xmlWriter.flush();
            xmlWriter.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return stringWriter.toString();
    }

    /**
     * 去掉声明头的(即<?xml...?>去掉)
     *
     * @param document
     * @param charset
     * @return
     */
    public static String documentToStringNoDeclaredHeader(Document document, String charset) {
        String xml = documentToString(document, charset);
        return xml.replaceFirst("\\s*<[^<>]+>\\s*", "");
    }

    /**
     * 解析XML为Document对象
     *
     * @param xml
     *            被解析的XMl
     * @return Document
     */
    public final static Element parseXml(String xml) {
        StringReader sr = new StringReader(xml);
        SAXReader saxReader = new SAXReader();
        Document document = null;
        try {
            document = saxReader.read(sr);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        Element rootElement = document != null ? document.getRootElement() : null;
        return rootElement;
    }

    /**
     * 获取element对象的text的值
     *
     * @param e
     *            节点的对象
     * @param tag
     *            节点的tag
     * @return
     */
    public final static String getText(Element e, String tag) {
        Element _e = e.element(tag);
        if (_e != null)
            return _e.getText();
        else
            return null;
    }

    /**
     * 获取去除空格的字符串
     *
     * @param e
     * @param tag
     * @return
     */
    public final static String getTextTrim(Element e, String tag) {
        Element _e = e.element(tag);
        if (_e != null)
            return _e.getTextTrim();
        else
            return null;
    }

    /**
     * 获取节点值.节点必须不能为空，否则抛错
     *
     * @param parent    父节点
     * @param tag       想要获取的子节点
     * @return          返回子节点
     */
    public final static String getTextTrimNotNull(Element parent, String tag) {
        Element e = parent.element(tag);
        if (e == null)
            throw new NullPointerException("节点为空");
        else
            return e.getTextTrim();
    }

    /**
     * 节点必须不能为空，否则抛错
     *
     * @param parent    父节点
     * @param tag       想要获取的子节点
     * @return          子节点
     */
    public final static Element elementNotNull(Element parent, String tag) {
        Element e = parent.element(tag);
        if (e == null)
            throw new NullPointerException("节点为空");
        else
            return e;
    }

    /**
     * 将文档对象写入对应的文件中
     * @param document      文档对象
     * @param path          写入文档的路径
     * @throws IOException
     */
    public final static void writeXMLToFile(Document document,String path) throws IOException{
        if(document==null||path==null){
            return;
        }
        XMLWriter writer = new XMLWriter(new FileWriter(path));
        writer.write(document);
        writer.close();
    }

    /**
     * 把原始的xml转换成map key为节点的路径，值为节点值 ，遇到重复节点用”[数字]“标识第几个节点
     * 如:<xml><list><test>test1</test><test>test2</test></list></xml> 会转换成
     * /xml/list[1]/test=test1 /xml/list[2]/test=test2
     * @param message
     * @return
     */
    public static Map<String, String> xml2Map(String message) {
        Map<String, String> data = new LinkedHashMap<String, String>();
        Document doc = null;
        try {
            doc = DocumentHelper.parseText(message);
        }
        catch (DocumentException e) {
            e.printStackTrace();
        }

        Element root = doc.getRootElement();
        String path = "/" + root.getName();
        element2Map(root, data, path);
        return data;
    }

    private static void element2Map(Element ele, Map<String, String> data, String path) {
        if(ele == null) {
            return;
        }
        List<Element> childrens = ele.elements();
        if(childrens != null && childrens.size() > 0) {
            Element pre = null;
            Element cur = null;
            Element next = null;
            int nodeIndex = 1;
            int length = childrens.size();
            for (int i = 0; i < length; i++) {
                cur = childrens.get(i);
                String nodePath = path + "/" + cur.getName();
                if(pre == null) {
                    if (length > 1){
                        next = childrens.get(i + 1);
                        if(next.getName().equals(cur.getName())) {
                            nodePath += "[" + nodeIndex + "]";
                            nodeIndex++;
                        }
                    }
                }
                else {
                    if(pre.getName().equals(cur.getName())) {
                        nodePath += "[" + nodeIndex + "]";
                        nodeIndex++;
                    }
                    else {
                        nodeIndex = 1;
                    }
                }
                element2Map(cur, data, nodePath);
                pre = cur;
            }
        }
        else {

            data.put(path, ele.getText());

        }

    }

    /**
     * 把map转换成xml
     * @param map
     * @return
     */
    public static String map2Xml(Map<String, String> map) {
        String xml = "";
       //根据map用dom4j创建Document
        Document doc = DocumentHelper.createDocument();
        Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, String> e = it.next();
            String key = e.getKey();
            String value = e.getValue();

            Element ele = DocumentHelper.makeElement(doc, key);
            ele.setText(value);
        }

        //格式化
        OutputFormat format = OutputFormat.createPrettyPrint();
        //format.setNewLineAfterDeclaration(true);
        format.setExpandEmptyElements(false);
        StringWriter out = new StringWriter();
        XMLWriter writer = new XMLWriter(out, format);
        try {
            writer.write(doc);
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        xml = out.toString();
        xml = xml.replaceAll("\\[\\d*\\]", "");
        return xml;
    }
}
